<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 15-7-2
 * Time: 下午10:40
 */

namespace Application\Base;


class mdlError extends mdlBase
{
    const READ_GROUP_STATIC_ERROR = "1:read static group file failure";
    static $errorStack = [];
    static private $_throwError = false;

    /**
     * 设置是否直接抛出异常
     * @param bool $open
     */
    static public function setThrowError($open = false)
    {
        self::$_throwError = $open;
    }

    /**
     * 设置错误
     * @param $message
     * @return bool
     * @throws \Exception
     */
    static public function setError($message)
    {
        $debug = debug_backtrace();
        $line = "";
        $file = "";
        if (isset($debug[0])) {
            $line = $debug[0]['line'];
            $file = $debug[0]['file'];
        }
        array_push(self::$errorStack, [$message, $line, $file]);
        if (self::$_throwError) {
            list($errno, $error) = self::_get($message);
            throw new \Exception($error, $errno);
        }
        return false;
    }

    /**
     * 获取第一个错误信息
     * @return array
     */
    static public function getFirstErrorInfo()
    {
        list($message, $line, $file) = current(self::$errorStack);
        list($errno, $error) = self::_get($message);
        return [
            'error' => $error,
            "errno" => $errno
        ];
    }

    /**
     * 获取第一个错误的错误编码
     * @return mixed
     */
    static public function getFirstErrno()
    {
        $error = self::getFirstErrorInfo();
        return $error['errno'];
    }

    /**
     * 获取第一个错误的错误内容
     * @return mixed
     */
    static public function getFirstError()
    {
        $error = self::getFirstErrorInfo();
        return $error['error'];
    }

    /**
     * 获取所有错误
     * @return array
     */
    static public function getAllError()
    {
        return self::$errorStack;
    }

    /**
     * 清理错误
     */
    static public function clearError()
    {
        self::$errorStack = [];
    }

    /**
     * 直接返回错误信息
     * @param string $error
     * @param bool $exit
     * @return bool
     */
    static public function response($error = "", $exit = true)
    {
        $o = new \stdClass();
        if ($error) {
            list($o->code, $o->msg) = explode(":", $error);
        } else {
            $o->code = self::getFirstErrno();
            $o->msg = self::getFirstError();
        }
        echo json_encode($o);
        $exit && exit();
        return false;
    }

    /**
     * 获取错误信息的基础方法
     * @param $message
     * @return array
     */
    private static function  _get($message)
    {
        $list = explode(":", $message);
        if (count($list) < 2) {
            $code = 0;
            $message = "";
        } else {
            list($code, $message) = $list;
            $code = empty($code) ? 0 : intval($code);
            $message = empty($message) ? "" : $message;
        }
        return [$code, $message];
    }
} 